package com.wzy.es.controller;

import org.elasticsearch.action.search.SearchRequestBuilder;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.search.suggest.Suggest;
import org.elasticsearch.search.suggest.SuggestBuilder;
import org.elasticsearch.search.suggest.completion.CompletionSuggestion;
import org.elasticsearch.search.suggest.completion.CompletionSuggestionBuilder;
import org.springframework.data.elasticsearch.core.ElasticsearchTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

@RestController
@RequestMapping("/suggest")
public class MovieSuggestController {
    @Resource
    private ElasticsearchTemplate elasticsearchTemplate;

    @GetMapping
    public List<String> get(String prefix) {
        ArrayList<String> list = new ArrayList<>();
        CompletionSuggestionBuilder completionSuggestionBuilder = new CompletionSuggestionBuilder("title")
                .prefix(prefix)
                .skipDuplicates(true)
                .size(10);
        SuggestBuilder suggestBuilder = new SuggestBuilder()
                .addSuggestion("title_suggestion", completionSuggestionBuilder);
        SearchRequestBuilder requestBuilder = elasticsearchTemplate.getClient()
                .prepareSearch("movies")
                .suggest(suggestBuilder)
                .setFetchSource(false);// 不查询其他无用字段

        SearchResponse response = requestBuilder.get();
        Suggest suggest = response.getSuggest();
        Suggest.Suggestion suggestion = suggest.getSuggestion("title_suggestion");
        List<CompletionSuggestion.Entry> entries = suggestion.getEntries();
        entries.forEach(e -> {
            List<CompletionSuggestion.Entry.Option> options = e.getOptions();
            options.forEach(op -> {
                String s = op.getText().toString();
                list.add(s);
            });
        });
        return list;
    }
}
